<template>
  <x-card hide-search>
    <template #title>
      <el-space>
        <x-button bus-type="insert" @click="methods.add"></x-button>
        <x-button bus-type="update" @click="methods.edit"></x-button>
        <x-button bus-type="view" @click="methods.view"></x-button>
        <x-button bus-type="del" @click="methods.del"></x-button>
      </el-space>
      <el-space>
        <el-input v-model="condition.name" placeholder="名称"></el-input>
        <x-button bus-type="query" @click="methods.query"></x-button>
      </el-space>
    </template>
    <template #main>
      <x-table v-model:selection="table.selection" v-bind="table" @page-change="methods.tablePageChange"></x-table>
    </template>
    <editor v-model:visable="editor.visable" v-bind="editor" @saved="methods.query"></editor>
  </x-card>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'

import elpUtil from '~/utils/elp'
import { DemoTableService } from '~/service/demo'
import { ITableColumn } from '~/components/xview/table/ITableColumn'
import { DemoTableQueryCondition } from '~/types/demo/DemoTableQueryCondition'
import { DemoTable } from '~/types/demo/DemoTable'
import { initTable } from '~/hooks/TableHooks'
import { EditorHooks } from '~/hooks'
import Editor from './editor.vue'

const editor = EditorHooks.init<DemoTable>()
const condition = reactive<DemoTableQueryCondition>(new DemoTableQueryCondition())

const methods = {
  add() {
    const model = {} as DemoTable
    editor.insert(model)
  },
  edit() {
    if (table.selection.length == 0) {
      elpUtil.msg.warning('请先选择需要编辑的数据行')
      return
    }
    editor.update(table.selection[0])
  },
  view() {
    if (table.selection.length == 0) {
      elpUtil.msg.warning('请先选择需要查看的数据行')
      return
    }
    editor.view(table.selection[0])
  },
  tablePageChange(page: number) {
    condition.paging.current = page
    methods.query()
  },
  async del() {
    if (table.selection.length == 0) return
    const ids = table.selection.map((t) => t.id)
    await DemoTableService.del(ids)
    elpUtil.msg.success('测试删除成功')
    methods.query()
  },
  async query() {
    const data = await DemoTableService.query(condition)
    table.pageCurrent = data.currentPage
    table.recordsTotal = data.recordsTotal
    table.tableData = data.data
  },
  dialogVisable(val: boolean) {
    editor.visable = val
  }
}

const table = initTable<DemoTable>([
  {
    label: 'ID',
    prop: 'id',
    width: 250
  },
  {
    label: '名称',
    prop: 'name',
    width: 200
  },
  {
    label: '字符串字段1',
    prop: 'textField1',
    width: 150
  },
  {
    label: '字符串字段2',
    prop: 'textField2',
    width: 150
  },
  {
    label: '数字字段1',
    prop: 'numberField1',
    width: 100
  },
  {
    label: '数字字段2',
    prop: 'numberField2',
    width: 100
  },
  {
    label: '备注',
    prop: 'remark'
  }
] as ITableColumn[])

methods.query()
</script>
